addpath(genpath('C:\Users\BCoe\matlab_code\new_magnet_tasks'))
%addpath(genpath('C:\_projects\bcoe\matlab_code\new_magnet_tasks'))
% http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/
% http://www.iconarchive.com/

home
clear;
task=mfilename;
close all
drawnow;
clear mex
pause(.2)
temp=pwd;
cd([PsychtoolboxRoot 'PsychContributed' filesep ]);
PsychHID('Version');
cd(temp)
clear temp;
%fprintf('INFO: please copy the 32-Bit libusb-1.0.dll from the PsychContributed folder into your C:\\WINDOWS\\system32\\ \n');

KbQueueCreate();
clear persistent
clear global
totalMemory=java.lang.Runtime.getRuntime.totalMemory;
freeMemory=java.lang.Runtime.getRuntime.freeMemory;

if freeMemory/totalMemory<.05
    fprintf('there is only %3.2f%% of free JAVA memory left\n -> exiting... please restart matlab\n',freeMemory/totalMemory*100);
    return
else
    fprintf('there is %3.2f%% of free JAVA memory left\n',freeMemory/totalMemory*100);
end

%% make sure the eye tracker is running before anything else
%enableCallbacks = 'PsychEyelinkDispatchCallback'; %special secret ninja hidden code
InitializeDummy=false;
if Eyelink2('Initialize', 'PsychEyelinkDispatchCallback')
    InitializeDummy=questdlg_offscreen('Eyelink is not properly connected. Initialize in Dummy mode?', ...
        'Eyelink is not connected!', ...
        'Yes','Quit','Yes');drawnow;
    if strcmp(InitializeDummy,'Yes')
        InitializeDummy=true;
        if Eyelink2('InitializeDummy', 'PsychEyelinkDispatchCallback')
            fprintf('InitializeDummy failed too\n')
            return;
        end
    else
        fprintf('cancled by user\n')
        return;
    end
end
Eyelink2('Command','clear_screen 0');


clear  ans

%%
fprintf('\nSTART\n')
c=define_colors(uint8(256));
%c.BACKGROUND=c.BLACK;
c.BACKGROUND=c.D_GREY;%2014-03-28
c.TTEXT=c.WHITE;
ec = EL_colors;
%ec.BACKGROUND=ec.BLACK;
ec.BACKGROUND=ec.D_GREY;
ec.GO=ec.GREEN;
ec.NG=ec.RED;
%match object colors-ish below
ec.TTEXT=ec.L_GREY;
ec.OBJ(1)=ec.BLUE;
ec.OBJ(2)=ec.GREEN;
ec.OBJ(3)=ec.YELLOW;% orange
ec.OBJ(4)=ec.RED;
ec.OBJ(5)=ec.L_YELLOW;% yellow
ec.OBJ(6)=ec.MAGENTA;
% eye position
EYE.fix=1000;
EYE.up=1001;
EYE.down=1002;
EYE.left=1003;
EYE.right=1004;
EYE.cell={EYE.right EYE.down EYE.left EYE.up };
% keyboard arrow button
KEY.up=38;
KEY.down=40;
KEY.left=37;
KEY.right=39;
KEY.cell={KEY.right KEY.down KEY.left KEY.up};
%
FORP.left=50;%int8('2');%
FORP.right=54;%int8('6');%
FORP.cell={FORP.left FORP.right };

% sidewinder gamepad
% SW.lefton='8224';
% SW.righton='16448';
% SW.leftoff='8192';
% SW.rightoff='16384';
%upside down sidewinder gamepad
SW.up=2001;
SW.down=2002;
SW.left=2003;
SW.right=2004;
SW.cell={SW.right SW.down SW.left SW.up};

loc_text={'Right','Down','Left','Up'};
effector='';
device=uint8(1);%default to keyboard
edf_name='edf_name';

MonitorPositions=get(0,'MonitorPositions');
%SECOND MONITOR SHOULD BE LEFT OF FIRST MONITOR
[~, ind]=min(MonitorPositions(:,1));
if ind~=size(MonitorPositions,1)
    warning('BCOE:SCREEN','screens are switched for some reason!!')
end
if size(MonitorPositions,1)==1
    screennum=0;
else
    screennum=2;
end

%re do this at screen
screenpixW=MonitorPositions(end,3);
screenpixH=MonitorPositions(end,4);

%% where are we ?
folder=fileparts(which('memory_task01'));%mfilename
cd(folder)
temp=pwd;
basefolder=temp(1:strfind(lower(temp),'bcoe')+4);
if isempty(basefolder)
    basefolder=temp(1:strfind(lower(temp),'brian')+5);
    if isempty(basefolder)
        error('you are not in the correct folder...')
    end
end
home_folder=[basefolder 'data\\'];

%wherearewe=questdlg_offscreen('Which Computer are you on?', ...
%    'Where are you?','ARM setup','Sham','Magnet','Sham');
wherearewe='ARM setup';
switch lower(wherearewe)
    % computer specific information
    case 'arm setup'
        if screenpixW==1920% laptop only
            distance2screen=24;%inches
            screenwidth=310*0.0393700787;  % mm 2 inches
            sheightinches=174*0.0393700787;% mm 2 inches
        else %screenpixW== 1280 i.e using arm mount
            distance2screen=24;% inches
            screenwidth=337*0.0393700787; % mm 2 inches
            sheightinches=271*0.0393700787; %mm 2 inches
        end
    case 'sham'
        screennum=1;
        armorbore=questdlg_offscreen('Using the ARM mount or in the sham?', ...
            'Where are you?','ARM','Bore','ARM');
        switch lower(armorbore)
            case 'arm'
                distance2screen=(24);% inches
                screenwidth=(337*0.0393700787); % mm 2 inches
                sheightinches=(271*0.0393700787); %mm 2 inches
            case 'bore'
                distance2screen=(23);% inches ???
                screenwidth=(17); % inches ???
                sheightinches=screenwidth*3/4;
                disp('dont know sham bore screen size yet');
                return
            otherwise
                disp('cancled by user')
                return
        end % switch lower(armorbore)
    case 'magnet'
        screennum=1;
        distance2screen=(57);% inches
        screenwidth=(18); % inches
        sheightinches=screenwidth*3/4;
    otherwise
        disp('cancled by user')
        return
end %switch wherearewe

home_folder=sprintf('%s%s',home_folder,task);
if isdir(home_folder)==0
    fprintf('making directory: %s\n',home_folder);
    mkdir(home_folder)
end
cd(home_folder)
clear ButtonName screenRect
uimenufcn(0,'WindowCommandWindow');
drawnow;
%% %%%%%%%%%%%%%%%%%%%%%%%%%
% % ASSIGN PARAMETERS   %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%
obj_cnt=6;
% First, try to load table of parameter names and set values
try
    % this should speed things along if your running a few studies on the same subject
    cd(home_folder)
    load('temp')
    for par = 1:size(Parameters,1)% assign each parameter in the table to its value
        eval([Parameters{par,1} '=''' Parameters{par,2} ''';']); % for string entries
    end
    sub_inits%#ok<NOPTS> % % check if it exists
    sub_code%#ok<NOPTS>% check if it exists
    if ~strcmp(kyou,datestr(now,'yyyy-mm-dd'))% check if it exists & ...
        error('not todays date');% if today's date doesn't match the date in the temp file force 'try' to fail
    end
    file_nb=sprintf('%02d',str2num(file_nb)+1)%#ok<NOPTS> % check if it exists & increment
    % TR%#ok<NOPTS>% check if it exists
    % t1eq_scans%#ok<NOPTS>% check if it exists
    fix_dur%#ok<NOPTS>% check if it exists
    tgt_dur%#ok<NOPTS>% check if it exists
    blk_dur%#ok<NOPTS>% check if it exists
    msk_dur%#ok<NOPTS>% check if it exists
    tgt_cnt%#ok<NOPTS>% check if it exists
    tgt_ecc%#ok<NOPTS>% check if it exists
    res_dur%#ok<NOPTS>
    out_dur%#ok<NOPTS>
    trial_limit%#ok<NOPTS>
    %R_Fix%#ok<NOPTS> % inter trial fixation duration
    %IB_Fix%#ok<NOPTS>
    %NOR%#ok<NOPTS> % number of repetitions5
    EoB%#ok<NOPTS>% =eye or button
    OSI%#ok<NOPTS>% =Object or Spatial
    %game%#ok<NOPTS>
    %gor%#ok<NOPTS>
    %EvenOdd%#ok<NOPTS>
catch parametertry
    % else start from defaults (in string format)
    parametertry.message
    parametertry.stack
    disp(' -> loading default settings');
    beep;pause(.2);beep;
    sub_inits='XXX';
    sub_code='00000';
    kyou=datestr(now,'yyyy-mm-dd');
    file_nb='00';
    fix_dur='2000';
    tgt_cnt='2';
    tgt_dur='750';
    blk_dur='750';
    msk_dur='2000';
    tgt_ecc='6';
    res_dur='tgt_cnt*1000';
    out_dur='1200';
    trial_limit='0';
    %R_Fix  ='800';
    %NOR='1';
    EoB='0'; % =eye(0) or button(1)
    OSI='0'; % Object(0), Spatial(1), or Instructed(2) memory task
    cd(home_folder)
    %save('temp','Parameters','kyou');    % saves temp data (still in string format)
end

clc
Parameters={...% variable_name,  value,  'discription',  string, number?
    'sub_inits',	sub_inits,		'Subjects 3 Initials (ABC)',                     's';...
    'sub_code',	    sub_code,		'Subjects 6 Digit Code (00000)',                 's';...
    'file_nb',		file_nb,		'File # (or run #, always 2 digits):',           's';...
    'fix_dur',	    fix_dur,        'Duration of Fixation',                          'n';...
    'tgt_cnt',	    tgt_cnt,        'Number of Targets',                             'n';...
    'tgt_dur',	    tgt_dur,        'Duration of Target',                            'n';...
    'blk_dur',	    blk_dur,        'Duration of Blank',                            'n';...
    'msk_dur',	    msk_dur,        'Duration of Mask',                              'n';...
    'tgt_ecc',	    tgt_ecc,        'Eccentricity of Target (from FIX in deg''s)',   'n';...
    'res_dur',	    res_dur,        'Duration for Response ',                        'n';...
    'out_dur',	    out_dur,        'Duration of Feedback ',                         'n';...
    'trial_limit',  trial_limit,    'Limit of trials (0=permute all)',               'n';...
    'EoB',          EoB,            'Eye(0) or Button(1)',                           'n';...
    'OSI',          OSI,            'Object(0), Spatial(1), or Instructed(2) Memory task',   'n';...
    };
save('temp','Parameters','kyou');
%now set the numeric data to numbers
for par= findincell(Parameters(:,4),'n')' % for numeric entries
    eval([Parameters{par,1} '=[' Parameters{par,2} '];']);
    eval([Parameters{par,1} '=(' Parameters{par,1} '(:));' ]); % force to vertical
end
clear par
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% define states (video presentation)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
i=uint8(1);
S=[];
S.WAIT  =i;    t_state{i}='Waiting';       i=i+1;
%S.T1EQ   =i;    t_state{i}='T1_Equ';        i=i+1;
%S.IB_FIX =i;    t_state{i}='InterBlock_Fix';i=i+1;
%S.R_FIX  =i;    t_state{i}='task_Fix';      i=i+1;
S.FIX     =i;   t_state{i}='Start_Fix';     i=i+1;
for ii =1:6% hard code 6 object & blank states will never use most
    eval(sprintf('S.OBJECT%d    =i;   t_state{i}=''Object%d'';       i=i+1;',ii,ii))
    eval(sprintf('S.BLANK%d     =i;   t_state{i}=''Blank%d'';        i=i+1;',ii,ii))
end
S.MASK    =i;   t_state{i}='Mask';         i=i+1;
S.RESPONSE=i;   t_state{i}='Response';     i=i+1;
S.OUTCOME =i;   t_state{i}='Outcome';      i=i+1;
S.ENDTASK =i;   t_state{i}='End_Task';     i=i+1;
%state_time(1:i-1)=0;
fnames=fieldnames(S);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% define state timing & update parameters
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
file_name=[Parameters{1,2} '.' kyou '_' Parameters{3,2} ];
update=2;
while update
    if update==1 % skip interface the first time to do calculations
        clc;
        drawnow;
        %home;
        fprintf('Duration of Paragigm: %dms or %d:%02.1f min.\n',max(state_end_time),floor(max(state_end_time)/60000), (rem(max(state_end_time)/60000*60,60)))
        %fprintf('Total # of Volumes: %6.2f \n',(max(state_end_time))/TR)
        %fprintf('TR=%d ms, TR''s per subblock: %d\n',TR, (mean(state_end_time(state_event==S.R_FIX)-state_start_time(state_event==S.FIX))*max_trials)/TR)
        %if floor(max(state_end_time)/TR)*TR<(max(state_end_time)/TR)*TR
        %    fprintf('... try %d or %dms \n', floor(max(state_end_time)/TR)*TR,         ceil(max(state_end_time)/TR)*TR)
        %end
        cd(home_folder)
        load('temp') % gets the string versions back
        [ParamInputs, update] = parameter_inputdlg(Parameters, ['Enter Parameters - ' file_name] );
        if isempty(ParamInputs);
            disp('Task Canceled');
            return
        end
        
        kyou=datestr(now,'yyyy-mm-dd');% force to todays date
        [Parameters{:,2}] = deal(ParamInputs{:});
        clear ParamInputs
        save('temp','Parameters','kyou');    % saves temp data (still in string format)
        %now set the numeric data to numbers
        for par= find(char(Parameters{:,4})=='n')' % for numeric entries
            eval([Parameters{par,1} '=[' Parameters{par,2} '];']);
            eval([Parameters{par,1} '=(' Parameters{par,1} '(:));' ]); % force to vertical
        end
        folder=[Parameters{1,2} '.' kyou];
        if ~exist(folder,'dir')
            eval(['mkdir ' folder]);
        end
        %cd(folder);
        file_name=[Parameters{1,2} '.' kyou '_' Parameters{3,2} ];
        edf_name=[num2str(dayofyear()) Parameters{1,2} Parameters{3,2}];% 8 char limit
        
        if exist([folder filesep file_name '.edf'],'file')
            yesno=questdlg_offscreen('File Exits! Overwrite it?','Be Careful!','Yes','No','No');
            if yesno(1)=='N'
                disp(['File Exists: ' file_name])
                update=1;
                file_nb=str2num(file_nb)+1;%#ok<*ST2NM> % increment
                if file_nb<10
                    file_nb=['0' num2str(file_nb)];
                else
                    file_nb=num2str(file_nb);
                end
                Parameters{3,2}=file_nb;
            end
            clear yesno;
        end
        
    end % if update==1
    if update>1, update=1;end
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % start do time stuff
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % trial randomization
    disp_cnt=4;% hard code 4 ... or min(4,round((tgt_cnt+1)/2)*2);
    disp_obj=uint8(permute_no_reps(obj_cnt,disp_cnt));
    disp_loc=uint8(permute_no_reps(disp_cnt,disp_cnt));
    % reduces repitions...
    for ii=1:ceil(length(disp_obj)/length(disp_loc))-1
        temp=permute_no_reps(disp_cnt,disp_cnt);
        disp_loc=[disp_loc; temp]; %#ok<AGROW>
    end
    if length(disp_loc)>length(disp_obj)
        disp_loc(length(disp_obj)+1:end,:)=[];
    end
    if trial_limit<=0% no limit
        trial_limit=length(disp_obj);
    end
    if trial_limit<length(disp_obj)
        disp_obj(trial_limit+1:end,:)=[];
        disp_loc(trial_limit+1:end,:)=[];
    end
    if tgt_cnt<disp_cnt
        tgts=disp_obj(:,1:tgt_cnt);
        dist=disp_obj(:,tgt_cnt+1:disp_cnt);
        goal=disp_loc(:,1:tgt_cnt);
        %[tgts dist]
    else
        clear temp
        dist=[];
        tgts=disp_obj(:,1:disp_cnt);
        goal=disp_loc;
        if tgt_cnt==4% last tgt of 4 can be # 1,2,4
            tempT=tgts';
            tempG=goal';
            ttt=local_shuffle([1 2 4],length(tgts))-1;
            tgts(:,4)=tempT((1:4:(numel(tempT)-1))+ttt);
            goal(:,4)=tempG((1:4:(numel(tempT)-1))+ttt);
        end
        if tgt_cnt>4% last tgt of 5 can be 1:4
            tempT=tgts';
            tempG=goal';
            ttt=local_shuffle(3,length(tgts))-1;
            tgts(:,5)=tempT((1:4:(numel(tempT)-1))+ttt);
            goal(:,5)=tempG((1:4:(numel(tempG)-1))+ttt);
            %test[tgts ttt']
            if tgt_cnt>5% tgt_cnt=disp_cnt+2
                tempT((1:4:(numel(tempT)-1))+ttt)=[];
                tempG((1:4:(numel(tempG)-1))+ttt)=[];
                %tempT=reshape(tempT,size(tgts,2)-2,size(tgts,1));
                ttt=local_shuffle(3,length(tgts))-1;
                tgts(:,6)=tempT((1:3:(numel(tempT)-1))+ttt);
                goal(:,6)=tempG((1:3:(numel(tempG)-1))+ttt);
                %[tgts ttt']
            end
        end
    end
    
    clear temp ttt tempT tempG
    max_trials=length(tgts);
    response=int8(zeros(max_trials,tgt_cnt,1)-1);
    correct=int8(zeros(max_trials,tgt_cnt,1)-1);
    RT=uint16(ones(max_trials,tgt_cnt)*-999);
    last5=0;
    % create state_vectors
    state_event=S.WAIT;
    state_duration=1000;
    for i = 1:max_trials
        
        state_event(end+1)=S.FIX; %#ok<SAGROW>
        state_duration(end+1)=fix_dur;%#ok<SAGROW>
        
        %state_event(end+1)=S.OBJECT;%#ok<SAGROW>
        for ii =1:tgt_cnt
            eval(sprintf('state_event(end+1)=S.OBJECT%d;',ii))
            state_duration(end+1)=tgt_dur;%#ok<SAGROW>
            eval(sprintf('state_event(end+1)=S.BLANK%d;',ii))
            state_duration(end+1)=blk_dur;%#ok<SAGROW>
        end
        state_event(end+1)=S.MASK;%#ok<SAGROW>
        state_duration(end+1)=msk_dur;%#ok<SAGROW>
        
        state_event(end+1)=S.RESPONSE;%#ok<SAGROW>
        state_duration(end+1)=res_dur;%#ok<SAGROW>
        
        state_event(end+1)=S.OUTCOME;%#ok<SAGROW>
        state_duration(end+1)=out_dur;%#ok<SAGROW>
    end %  for i = 1:max_trials
    state_event(end+1)=S.ENDTASK;%#ok<SAGROW>
    state_duration(end+1)=0;%#ok<SAGROW>
    
    state_duration=uint16(state_duration(:));
    state_event=uint8(state_event(:));
    state_end_time=cumsum(single(state_duration));
    state_start_time=[0; state_end_time(1:end-1)];
    % [single(state_event) single(state_duration) state_start_time state_end_time]
    cd(home_folder)
    save('temp','Parameters','kyou');    % saves temp data (still in string format)
    file_name=[Parameters{1,2} '.' kyou '_' Parameters{3,2} ];
end
change_state_time=single(zeros(length(state_end_time),2));
MaskRot=uint16((local_shuffle(4,length(tgts))-1)*90);
uimenufcn(0,'WindowCommandWindow');
cd(folder);

%% start these buffers
if any(EoB)
    switch lower(wherearewe)
        case 'arm setup'
            whatarewe=questdlg_offscreen('Which input Device?', ...
                'Which input device are you using?', ...
                'keyboard','SideWinder','either','either');
            switch whatarewe
                case 'keyboard'% block SideWinder
                    device=1;
                case 'SideWinder'% block keyboard
                    device=2;
                case 'either'% debug mode = either
                    device=3;
                otherwise
                    disp('cancled by user. not a supported device')
                    return
            end
            clear whatarewe
        case 'sham'
            device=4; % FORP button box box
        case 'magnet'
            device=4; % FORP button box box
    end
end

percor=0;
index=1;
trial=0;
state=double(state_event(index));
event=state;
r_time=0;
r_TR=0;
r_state=0;
%INT_5=single(zeros(ceil((max(state_end_time))/TR),1));
%subblock=0;
%sb=0; % subblock
%g=0;%which game
eyesample=uint16(200); % how many data point to save for eye position
ex=single(cumsum(ones(eyesample,1))); % force vertical
ey=ex;
et=ex;
exs=ex;
eys=ex;
speed=ex;

%% screen
try
    if ~InitializeDummy
        hideCursor;
    end
    KbQueueStart;
    warning('off', 'PTB3:KbQueueBusy')
    ListenChar(2);% BLOCK keyboard from MATLAB
    warning('on', 'PTB3:KbQueueBusy')
    lastwarn('')
    %Screen('Preference','SkipSyncTests',1);
    %Screen ('Preference','VisualDebugLevel',1);% but i had 3
    %Screen('Preference','SuppressAllWarnings',1);
    oldLevel = Screen('Preference', 'VisualDebugLevel', 1); %level 1: error only
    oldEnableFlag = Screen('Preference', 'SuppressAllWarnings', 1);
    Screen('Preference', 'SkipSyncTests', 1);
    
    [w, wRect]=Screen('OpenWindow', screennum);
    %[w, wRect]=Screen('OpenWindow', screennum, 0,[],32,2);
    Screen(w,'BlendFunction',GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    % needed for proper anti-aliasing (smoothing) by Screen('DrawLines'), Screen('DrawDots') and for
    % drawing masked stimuli with the Screen('DrawTexture') command. See DotDemo,
    % LinesDemo, AlphaImageDemo, GazeContingentDemo for a few applications of
    % alpha-blending.
    pause(.01);
    Screen('fillrect',w,c.BACKGROUND);
    Screen('flip',w);
    clc;
    screenpixW=wRect(RectRight);
    screenpixH=wRect(RectBottom);
    c_x=round(double(screenpixW/2)); % the stupid text commands require a double for pixels placement
    c_y=round(double(screenpixH/2));
    Screen('TextStyle',w,1);% 0=plain, 1=bold, 2=italics, 3=1&2,  4=underlined, 5=4&1,6=4&2, 7=4&3. rem(?,8)
    Screen('TextFont',w,'Tahoma');
    Screen('TextSize',w,40);
    centertextY=c_y-40*.8;
    
    dphs = atan2(screenwidth/2,distance2screen)*180/pi;%degrees per half screen
    ppd = (screenpixW)/2/dphs; %pixels/degree
    
    % http://www.iconarchive.com/
    % http://psychtoolbox.org/FaqImageTransparency
    [MaskI,   ~, alpha0] = imread('Mask.png');
    % FORCE ALL TO 130 x 130
    [Object1, ~, alpha1] = imread('blue_square2.png');
    [Object2, ~, alpha2] = imread('green_circle3.png');
    [Object3, ~, alpha3] = imread('orange_X2.png');
    [Object4, ~, alpha4] = imread('red_stop2.png');
    [Object5, ~, alpha5] = imread('yellow_triange2.png');
    [Object6, ~, alpha6] = imread('purple_dimond2.png');
    [spatial, ~, alphaS] = imread('spatial2.png');
    %         [Object1 map alpha1] = imread('blue-snow-icon.png');
    %         [Object2 map alpha2] = imread('shamrock-icon.png');
    %         [Object3 map alpha3] = imread('orange-icon.png');
    %         [Object4 map alpha4] = imread('Strawberry2-icon.png');
    %         [Object5 map alpha5] = imread('sun-icon.png');
    %         [Object6 map alpha6] = imread('grape-icon.png');
    %         [spatial map alphaS] = imread('Soccer-icon.png');
    [check, ~, alphac] = imread('Action-ok-icon.png');
    [batsu, ~, alphae] = imread('Delete-icon.png');
    [arrow_R, ~, alphaR] = imread('black_right.png');
    [arrow_D, ~, alphaD] = imread('black_down.png');
    [arrow_L, ~, alphaL] = imread('black_left.png');
    [arrow_U, ~, alphaU] = imread('black_up.png');
    
    %MaskI(:,:,4) = alpha0(:,:); % no alpha
    Object1(:,:,4) = alpha1(:,:);
    Object2(:,:,4) = alpha2(:,:);
    Object3(:,:,4) = alpha3(:,:);
    Object4(:,:,4) = alpha4(:,:);
    Object5(:,:,4) = alpha5(:,:);
    Object6(:,:,4) = alpha6(:,:);
    spatial(:,:,4) = alphaS(:,:);
    check(:,:,4) = alphac(:,:);
    batsu(:,:,4) = alphae(:,:);
    arrow_R(:,:,4) = alphaR(:,:);
    arrow_D(:,:,4) = alphaD(:,:);
    arrow_L(:,:,4) = alphaL(:,:);
    arrow_U(:,:,4) = alphaU(:,:);
    clear map  alpha0 alpha1 alpha2 alpha3 alpha4 alpha5 alpha6 alphaS alphac alphae alphaU alphaD alphaL alphaR
    Mask=Screen('MakeTexture',w,MaskI);
    Objects(1)=Screen('MakeTexture',w,Object1);
    Objects(2)=Screen('MakeTexture',w,Object2);
    Objects(3)=Screen('MakeTexture',w,Object3);
    Objects(4)=Screen('MakeTexture',w,Object4);
    Objects(5)=Screen('MakeTexture',w,Object5);
    Objects(6)=Screen('MakeTexture',w,Object6);
    Spatial=Screen('MakeTexture',w,spatial);
    OK=Screen('MakeTexture',w,check);
    NG=Screen('MakeTexture',w,batsu);
    Arrow(1)=Screen('MakeTexture',w,arrow_R);
    Arrow(2)=Screen('MakeTexture',w,arrow_D);
    Arrow(3)=Screen('MakeTexture',w,arrow_L);
    Arrow(4)=Screen('MakeTexture',w,arrow_U);
    
    
    OBJ_radius=size(Object1,1)/2;% radius of stim
    clear MaskI Object1 Object2 Object3 Object4 Object5 Object6 spatial check batsu arrow_R arrow_D arrow_L arrow_U
    OBJ_ang2=(OBJ_radius)/ppd;
    OBJ_rect=round([-1 -1 1 1]*OBJ_radius); % stimulus circl)e
    eye_win =round([-1 -1 1 1]*ppd*(OBJ_ang2+1));% radial angle of square window around target to accept eye
    fix_b=round([c_x c_y c_x c_y]+([-1 -1	1 1]*ppd*.1)); % fixation middle
    fix_a=round([c_x c_y c_x c_y]+([-1 -1	1 1]*ppd*.3)); % fixation circle
    tgt_XY=[];
    [tgt_XY(:,1), tgt_XY(:,2)]=polar2cart((0:(360/4):359),repmat(tgt_ecc,1,4)*ppd,0); % hard code 4 display disp_locs
    % [ t_XY(:,1) t_XY(:,2)]=polar2cart(t_ang_ecc(:,1),t_ang_ecc(:,2),1);
    % [ s_XY(:,1) s_XY(:,2)]=polar2cart(s_ang_ecc(:,1),s_ang_ecc(:,2),1);
    %tgt_XY=([-tgt_ecc 0; tgt_ecc 0; ]*ppd);
    fix_rect=OBJ_rect+[c_x c_y c_x c_y];
    tgt_rect=[];
    for i=1:length(tgt_XY) % for use with mac's LeToRiBo rect shite
        tgt_rect(i,:)=round([tgt_XY(i,:) tgt_XY(i,:)]+fix_rect); %#ok<SAGROW>
    end
    temp=[0,0; tgt_XY];% fixation and tgts
    for i=1:size(temp,1)
        eye_window{i}=round([temp(i,:) temp(i,:)]+eye_win+[c_x c_y c_x c_y]); %#ok<SAGROW> % for use with mac's LeToRiBo rect shite
    end
    eye_ontgt=false;
    %expand eye windows to be more open ended
    eye_window{2}(3)=round(eye_window{2}(3)+ppd*2);
    eye_window{3}(4)=round(eye_window{3}(4)+ppd*2);
    eye_window{4}(1)=round(eye_window{4}(1)-ppd*2);
    eye_window{5}(2)=round(eye_window{5}(2)-ppd*2);
    Pen=4;
    eye_cue=round([-1 -1 1 1]*ppd*1.5+[c_x c_y c_x c_y]);
    hand_cue=round([[c_x c_x c_x c_x c_x c_x]-1;c_y c_y c_y c_y c_y c_y]+[[1.5 0 0 -1.5 -1.5 1.5];[.97 -1.6 -1.6 .97 .97 .97]]*ppd);
    clear tgt_XY  OBJ_size eye_win temp
    clear MaskI Object1 Object2 Object3 Object4 Object5 Object6
    
    
    h2=update_info;
    
    %% do Eyelink after Screen
    el = EyelinkInitDefaults(w);%el=elglobal; %make it local and usable
    %their default is really bad:
    el.backgroundcolour = c.BACKGROUND(1);% bcoe
    el.foregroundcolour = c.TTEXT(1);% bcoe
    el.msgfontcolour    = c.M_GREY(1);% bcoe
    el.imgtitlecolour   = c.M_GREY(1);% bcoe
    el.calibrationtargetcolour=el.foregroundcolour;
    %el.eyeimgsize=screenpixW/20+10;
    %el.msgfont='Tahoma';
    el.msgfontsize=15;%12
    %el.imgtitlefont='Tahoma';
    el.imgtitlefontsize=12;
    EyelinkUpdateDefaults(el); % need to update el on the host
    
    % make sure that we get gaze data from the Eyelink
    Eyelink2('Command','calibration_type = HV5');
    
    Eyelink2('Command','file_event_filter = LEFT,RIGHT, AREA, SACCADE, FIXATION, BLINK, MESSAGE, BUTTON, INPUT');%sets which events will be written to the EDF file.
    Eyelink2('Command','link_event_filter = LEFT,RIGHT, AREA, SACCADE, FIXATION, BLINK, MESSAGE, BUTTON, INPUT');%sets which types of events will be sent through link
    
    status=Eyelink2('Command','file_sample_data = LEFT,RIGHT,GAZE,AREA,GAZERES,HREF,PUPIL,STATUS,INPUT,BUTTON,HMARKER');
    if status~=0
        disp('file_sample_data error')
    end
    status=Eyelink2('Command','link_sample_data = LEFT,RIGHT,GAZE,AREA,GAZERES,HREF,PUPIL,STATUS,INPUT,BUTTON,HMARKER');
    if status~=0
        disp('link_sample_data error')
    end
    
    status=Eyelink2('Command','inputword_is_window = ON');
    if status~=0
        disp('inputword_is_window error')
    end
    
    openfile = Eyelink2('OpenFile',[edf_name,'.edf']);
    if openfile~=0
        ttext='Task Aborted: Cannot create EDF file';
        DrawFormattedText(w,ttext,'center',centertextY,c.ORANGE);
        Screen('flip',w);
        Eyelink2('Command','clear_screen 0');
        Eyelink2('Command',sprintf('draw_text %d %d %d %s ',round(c_x),round(c_y)-100,ec.L_GREY,ttext));
        fprintf('%s: \n',ttext,edf_name);
        Eyelink2('SetOfflineMode');
        Eyelink2('Shutdown');
        pause(1);
        Screen('Closeall');
        KbQueueRelease();
        ListenChar(0);
        return;
    end %openfile~=0
    mouse_adj=0;% for InitializeDummy
    if InitializeDummy%Eyelink2('isconnected')>0%~= -1 &
        ttext='use PC mouse to emulate eye (Hit the space bar)';
        if screennum>0
            mouse_adj=MonitorPositions(screennum,1)-1;
        end
        SetMouse(c_x+mouse_adj,c_y);
        ShowCursor('CrossHair');
    else
        ttext='Hit the space bar to calibrate eye';
        SetMouse(c_x*3,c_y);
        hideCursor;
    end % InitializeDummy%
    DrawFormattedText(w,ttext,'center',(centertextY),(c.TTEXT));
    Screen('flip',w);
    Eyelink2('Command',sprintf('draw_text %d %d %d %s ',round(c_x),round(c_y)-100,ec.L_GREY,ttext));
    fprintf('%s\n',ttext);
    update_info(h2,{sprintf('%s\n',ttext)})
    keyCode=0;
    ii=0;
    while keyCode~=32% SPACE on pcwin
        [keyPress, keyCodes]= Kb_bcoe();
        if keyPress
            keyCode=keyCodes(1);
            if keyCode==27 % esc key
                ttext='Task Aborted';
                DrawFormattedText(w,ttext,'center',centertextY,c.ORANGE);
                Screen('flip',w);
                Eyelink2('Command','clear_screen 0');
                Eyelink2('Command',sprintf('draw_text %d %d %d %s ',round(c_x),round(c_y)-100,ec.L_GREY,ttext));
                fprintf('%s\n',ttext);
                update_info(h2,{sprintf('%s\n',ttext)});
                pause(1);
                Screen('Closeall');
                KbQueueRelease();
                ListenChar(0);
                return
            end
        end %keyPress
        ii=ii+1;
        if ii>1000000
            ttext='timed out';
            DrawFormattedText(w,ttext,'center',centertextY,c.ORANGE);
            Screen('flip',w);
            Eyelink2('Command','clear_screen 0');
            Eyelink2('Command',sprintf('draw_text %d %d %d %s ',round(c_x),round(c_y)-100,ec.L_GREY,ttext));
            fprintf('%s\n',ttext);
            update_info(h2,{sprintf('%s\n',ttext)});
            pause(1);
            Screen('Closeall');
            KbQueueRelease();
            ListenChar(0);
            return
        end% ii>1000000
    end% while keyCode~=32
    keyPress=0;
    keyCode=0;
    lastkeyCode=0;
    Screen('flip',w);
    Eyelink2('Command','clear_screen 0');
    el.callback = ''; %???
    if  ~InitializeDummy
        ttext=' entered EyelinkDoTrackerSetup\n';
        fprintf('%s\n',ttext);
        update_info(h2,{sprintf('%s\n',ttext)});
        EyelinkDoTrackerSetup(el,el.ENTER_KEY);
        ttext='  exited EyelinkDoTrackerSetup\n';
        fprintf('%s\n',ttext);
        update_info(h2,{sprintf('%s\n',ttext)})
        eye_used = Eyelink2('EyeAvailable'); % get eye that's tracked
        %if eye_used == el.BINOCULAR; % if both eyes are tracked
        %    eye_used = el.LEFT_EYE; % use left eye
        %end
    else
        eye_used='mouse';
        fprintf('EL1k not connected\n')
    end% ~InitializeDummy
    clear el
    pause(.5)
    %% wait for magnet/keypress to start
    if strmatch(lower(wherearewe),'arm setup')
        ttext='press spacebar to start';
        pass=32;% 'space bar' on pcwin
    else
        ttext='waiting for magnet to start';
        pass=48+5;% '5%' on pcwin the new mri trigger
    end
    DrawFormattedText(w,ttext,'center',centertextY,c.TTEXT);
    Screen('flip',w);
    Eyelink2('Command',sprintf('draw_text %d %d %d %s ',round(c_x),round(c_y)-100,ec.L_GREY,ttext));
    fprintf('%s\n',ttext);
    update_info(h2,{sprintf('%s\n',ttext)});    
    KbQueueFlush();
    keyPress=0;
    keyCode=0;
    lastkeyCode=0;% anti hammering
    while keyCode~=pass
        [keyPress, keyCodes,keyTimes]= Kb_bcoe();
        if keyPress
            keyCode=keyCodes(1);
            if keyCode~=lastkeyCode% anti hammering
                lastkeyCode=keyCode;
                if keyCode==27% ESC on pcwin
                    ttext='Task Aborted';
                    DrawFormattedText(w,ttext,'center',centertextY,c.ORANGE);
                    Screen('flip',w);
                    Eyelink2('Command','clear_screen 0');
                    Eyelink2('Command',sprintf('draw_text %d %d %d %s ',round(c_x),round(c_y)-100,ec.L_GREY,ttext));
                    fprintf('%s\n',ttext);
                            update_info(h2,{sprintf('%s\n',ttext)});                    
                    Eyelink2('CloseFile');
                    Eyelink2('SetOfflineMode');
                    Eyelink2('Shutdown');
                    pause(1);
                    Screen('Closeall');
                    KbQueueRelease();
                    ListenChar(0);
                    return
                end
            end %if keyCode~=lastkeyCode
        else
            lastkeyCode=0;
        end%if keyPress
    end %while keyCode~=pass
    clear pass
    keyPress=0;
    keyCode=0;
    lastkeyCode=0;% anti hammering
    clc;
    home;
    Eyelink2('Command','clear_screen 0');
    trial=0;
    outtext='';
    ttext='';
    count={};
    lastwarn('')
    samples=[];
    eventsIN=[];
    KbQueueFlush();
    Eyelink2('StartRecording'); % messages must be AFTER StartRecording and require SPRINTF to convert floats to strings
    Eyelink2('Message',char([82 101 99 111 114 100 101 100 32 98 121 32 66 67 79 69]));
    Eyelink2('Message','RETRACE_INTERVAL: 16.667')
    Eyelink2('Message',sprintf('disttoscreen %0.2f sheightinches %0.2f swidthinches %0.2f PPD %0.2f screenpixW %0.0f screenpixH %0.0f',distance2screen,sheightinches,screenwidth,ppd,screenpixW,screenpixH));
    %% finally start actual task
    Screen('flip',w);
    abs_start_time=round(GetSecs*1000);
    EL1k_start_time = round(Eyelink2('TrackerTime')*1000);
    Eyelink2('Message',sprintf('abs_start_time= %d',abs_start_time));% requires SPRINTF
    Eyelink2('Message',sprintf('EL1k_start_time= %d',EL1k_start_time));% requires SPRINTF
    Eyelink2('Message','SYNCTIME'); % old????
    change_state_time(index,:)=[single(state) 0];
    fred=round(GetSecs*10000);% check loop time in usecs
    my_timer=single(zeros(1,2000));
    %fred=cell(length(fieldnames(S)),1);%check drawing time of eyelink 6-7 ms
    while state < S.ENDTASK
        %Screen('fillrect',w,c.BACKGROUND); % done automatically with 'flip' except in debug mode
        switch state_event(index+1) % draw next state to buffer
            case S.FIX
                Screen('filloval',w,c.BLACK,fix_a);  % draw fixation
                Screen('filloval',w,c.BACKGROUND,fix_b);  % draw fixation 2/2
                
            case {S.OBJECT1 S.OBJECT2 S.OBJECT3 S.OBJECT4 S.OBJECT5 S.OBJECT6}
                whichObj= find(state_event(index+1)==[S.OBJECT1 S.OBJECT2 S.OBJECT3 S.OBJECT4 S.OBJECT5 S.OBJECT6]);
                switch OSI
                    case 0 % Object
                        Screen('DrawTexture',w,Objects(tgts(trial,whichObj)));% center by default
                        Screen('filloval',w,c.BLACK,fix_b);  % draw fixation 2/2
                    case 1 % Spatial
                        Screen('DrawTexture',w,Spatial,[],tgt_rect(goal(trial,whichObj),:));
                        Screen('filloval',w,c.BLACK,fix_a);  % draw fixation
                        Screen('filloval',w,c.BACKGROUND,fix_b);  % draw fixation 2/2
                    case 2 % Instructed
                        Screen('DrawTexture',w,Arrow(goal(trial,whichObj)));% center by default
                        Screen('filloval',w,c.BACKGROUND,fix_a);  % draw fixation
                        Screen('filloval',w,c.BLACK,fix_b);  % draw fixation 2/2
                end
            case {S.BLANK1 S.BLANK2 S.BLANK3 S.BLANK4 S.BLANK5 S.BLANK6}
                % should auto draw blank....
                switch OSI
                    case 0 % Object
                        Screen('filloval',w,c.BLACK,fix_b);  % draw fixation 2/2
                    case 1 % Spatial
                        Screen('filloval',w,c.BLACK,fix_a);  % draw fixation
                        Screen('filloval',w,c.BACKGROUND,fix_b);  % draw fixation 2/2
                    case 2 % Instructed
                        Screen('filloval',w,c.BACKGROUND,fix_a);  % draw fixation
                        Screen('filloval',w,c.BLACK,fix_b);  % draw fixation 2/2
                end
            case S.MASK
                Screen('DrawTexture',w,Mask,[],[],double(MaskRot(trial)));% center by default (rand rotate 0    90   180   270)
                Screen('filloval',w,c.BLACK,fix_b);  % draw fixation 2/2
                
            case {S.RESPONSE S.OUTCOME}% redraw so i can add feedback
                Screen('filloval',w,c.BLACK,fix_b);  % draw fixation 2/2
                switch OSI
                    case 0 % Object
                        Screen('DrawTextures',w,Objects(disp_obj(trial,:)),[],tgt_rect(disp_loc(trial,:),:)');
                    case {1 2} % Spatial; case 2 % Instructed
                        Screen('DrawTextures',w,Spatial,[],tgt_rect');% center by default
                end
                %for debugging
                % for ii = 1:4
                %   Screen('FrameRect', w,c.BLUE, eye_window{ii+1} );
                %   DrawFormattedText(w,num2str(ii),tgt_rect(ii,1),tgt_rect(ii,2),c.BLUE);
                % end
            case S.ENDTASK
        end% switch state_event(index+1) % draw next state to buffer
        
        % poll keyboard buffer every other per millisecond
        event_time=round(GetSecs*1000-abs_start_time);
        last_time=[event_time event_time+1];
        while event_time < state_end_time(index) & state < S.ENDTASK  %#ok<*AND2> (switch one filp before time)
            fred=round(GetSecs*10000);% check loop time in usecs
            if last_time(1)+2<event_time% check keyboard buffer once per 2 millisecond
                [keyPress, keyCodes, keyTimes]= Kb_bcoeMS(abs_start_time);
                last_time(1)=event_time;
                if ~keyPress,
                    lastkeyCode=0;
                end
            else
                keyPress=false;
                keyCodes=0;
                keyTimes=0;
            end
            if keyPress % first check keyboard
                if keyCodes(1)~=lastkeyCode% anti hammering
                    keyCode=keyCodes(1);
                    keyTime=keyTimes(1);
                    lastkeyCode=keyCode;
                    switch keyCode
                        %case 53 %keyboard 5% % magnet trigger
                        %   INT_5(ceil(event_time/TR))=event_time;
                        %   Eyelink2('Message', sprintf('TRtrigger: %d: TRtrigger: %0.2f',keyCode,event_time));% requires SPRINTF
                        %   keyPress=false;
                        %   keyCode=-1;% added 23_apr_2009 ignore INT_5
                        %   keyTime=0;
                        case 27% ESC on pcwin
                            ttext='(ESC pressed)';
                            Screen('fillrect',w,c.BACKGROUND); % done automatically with 'flip' except in debug mode
                            DrawFormattedText(w,ttext,'center',centertextY,c.ORANGE);
                            Screen('flip',w);
                            Eyelink2('Command','clear_screen 0');
                            Eyelink2('Command',sprintf('draw_text %d %d %d %s ',round(c_x),round(c_y)-100,ec.L_GREY,ttext));
                            fprintf('%s\n',ttext);
                            update_info(h2,{sprintf('%s\n',ttext)})
                            state = S.ENDTASK; % S.ENDTASK to exit
                            Eyelink2('Message', sprintf('state: %s(%d): %d (ESC pressed)', t_state{state},state,event_time));% requires SPRINTF
                            change_state_time(index,:)=[single(state) keyTime];
                            count={};
                            keyPress=false;
                            keyCode=-1;
                            keyTime=0;
                        case KEY.cell
                            if bitget(device,1)% using keyboard?
                                [keyCode, loc]=intersect([KEY.cell{:}],keyCode);% 'find' takes longer
                                effector='Keyboard';
                                Eyelink2('Message', sprintf( 'keyCode  =%5d: Location=%6s: Time=%10d: Input=%s',keyCode,loc_text{loc},keyTime,effector));% requires SPRINTF
                                if state~=S.RESPONSE || response(trial,CR)>=0 || EoB==0 % not too early or late, hasn't over responded OR it's the eye that counts
                                    keyPress=false;
                                    keyCode=0;
                                    keyTime=0;
                                    beep;
                                end
                            end % using keyboard?
                        case FORP.cell
                            if bitget(device,4) & sb*t>0 % using FORP and have valid index
                                [keyCode, loc]=intersect([FORP.cell{:}],keyCode);% 'find' takes longer
                                effector='FORP';
                                Eyelink2('Message', sprintf( 'keyCode  =%5d: Location=%6s: Time=%10d: Input=%s',keyCode,loc_text{loc},keyTime,effector));% requires SPRINTF
                                if state~=S.RESPONSE || response{sb}(t)>=0 || EoB(sb)==0 % not too early or late, hasn't over responded OR it's the eye that counts
                                    keyPress=false;
                                    keyCode=0;
                                    keyTime=0;
                                    beep;
                                end
                            end % using FORP?
                        otherwise
                            keyPress=false;
                            keyCode=0;
                            keyTime=0;
                            beep;
                    end % switch keyCode
                end%keyCodes(1)~=lastkeyCode% anti hammering
            else% check EL1k
                if state>=S.WAIT  % clear queued data
                    if last_time(2)+2<event_time% check buffers once per 2 millisecond
                        last_time(2)=event_time;
                        if InitializeDummy
                            samples=zeros(20,1);%fudge data to match Eyelink
                            samples(1)=event_time+EL1k_start_time;
                            samples(2)=200;
                            [samples(15),samples(17)] =GetMouse;
                            samples(15)=samples(15)-mouse_adj;% for multscreen
                            last_time(2)=last_time(2)+2; %check less frequently
                            %samples=samples'
                        else
                            [samples, eventsIN] = Eyelink('GetQueuedData');
                            %[samples, eventsIN, drained] =get_eye_data; only created to see how often its called
                        end
                        if ~isempty(samples) %& EoB==0% eye check even if not used to keep gooddata-eyesample accurate
                            %% check eye data
                            gooddata=samples(2,:)==200 & samples(1,:)>0;
                            %gooddata= samples(1,:)>0;
                            %gooddata=check_eye_data(samples); % only created to see how often its called
                            sumgooddata=sum(gooddata);
                            if sumgooddata>eyesample
                                try
                                    gooddata(1:sumgooddata-eyesample)=false; % truncate if too long
                                    sumgooddata=sum(gooddata);
                                catch truncate
                                    error('found error, bitches!')% if this error does show, use eyesample+1 in prev truncate line
                                end
                            end
                            if sumgooddata>0
                                % clear old eye traces in debug mode
                                %Screen('drawdots',w, round(double([exs(end-50:end); eys(end-50:end)])),5,c.BACKGROUND );
                                et(1:sumgooddata)=[];
                                ex(1:sumgooddata)=[];
                                ey(1:sumgooddata)=[];
                                et(eyesample-sumgooddata+1:eyesample)=samples(01,gooddata)-EL1k_start_time;
                                ex(eyesample-sumgooddata+1:eyesample)=samples(15,gooddata);
                                ey(eyesample-sumgooddata+1:eyesample)=samples(17,gooddata);
                                exs=([mean(ex(1:2)); ((ex(1:end-2)+ex(2:end-1)+ex(3:end))/3); mean(ex(end-1:end))]);
                                eys=([mean(ey(1:2)); ((ey(1:end-2)+ey(2:end-1)+ey(3:end))/3); mean(ey(end-1:end))]);
                                speed=xyt2speed(exs(:),eys(:),et(:))/ppd;
                                % drawnew eye traces in debug mode
                                % Screen('drawdots',w, round(double([exs(end-50:end); eys(end-50:end)])),5,c.ORANGE);
                                % Screen('flip',w,0,1,2);% dont clear  & don't sync at all
                                if mean(speed(eyesample-5:eyesample))<50% eye stopped
                                    loc=IsInRectS(ex(eyesample),ey(eyesample), eye_window(2:end)); % in a tgt rect?
                                    if loc
                                        if eye_ontgt~=loc %antihammering
                                            eye_ontgt=loc;
                                            effector='Eye_Window';
                                            keyCode=EYE.cell{loc};
                                            keyTime=et(eyesample-5);
                                            Eyelink2('Message', sprintf( 'keyCode  =%5d: Location=%6s: Time=%10d: Input=%s',keyCode,loc_text{loc},keyTime,effector));% requires SPRINTF
                                            if state==S.RESPONSE && response(trial,CR)==-1 && EoB==0 % not too early or late, hasn't over responded & it's the eye that counts
                                                keyPress=true;
                                            else
                                                keyTime=0;
                                                keyCode=0;
                                                beep;
                                            end
                                        end % if ~eye_ontgt %antihammering
                                    else
                                        eye_ontgt=false;
                                    end%loc
                                end % mean(speed(eyesample-5:eyesample))<50
                            end %if sumgooddata>0
                            
                            %% check sidewinder
                            if bitget(device,2) & sb*t>0
                                if ~isempty(eventsIN),
                                    sidewinder=eventsIN(:,eventsIN(2,:)==25);
                                    if any(sidewinder)
                                        keyCodes=sidewinder(3,:);
                                        keyTimes=sidewinder(1,:)-EL1k_start_time;
                                        [keyCode, loc,loc2]=intersect([SW.cell{:}],keyCodes);
                                        if any(keyCode) && length(keyCode)==1 % only except one key press per 2ms
                                            effector='sidewinder';
                                            keyTime=keyTimes(loc2);
                                            Eyelink2('Message', sprintf( 'keyCode  =%5d: Location=%6s: Time=%10d: Input=%s',keyCode,loc_text{loc},keyTime,effector));% requires SPRINTF
                                            if state==S.RESPONSE && response(trial,CR)>=0 && EoB==1 % not too early or late, hasn't over responded & it's the button that counts
                                                keyPress=true;
                                            else
                                                keyTime=0;
                                                keyCode=0;
                                                beep;
                                            end
                                        else
                                            beep;
                                        end
                                    end %if any(sidewinder)
                                end% ~isempty(eventsIN)
                            end %bitget(device,2)
                        end % if ~empty(samples)
                    else % last_time(2)+2<event_time% check buffer once per 2 millisecond
                        samples=[];
                        eventsIN=[];
                    end % last_time(2)+2<event_time% check buffer once per 2 millisecond
                end%if state>=S.WAIT
            end % keyPress
            if keyPress && response(trial,CR)==-1
                Eyelink2('Message', sprintf('Response%d=%5d: Location=%6s: Time=%10d (%s)',CR,keyCode,loc_text{loc},keyTime,effector));% requires SPRINTF
                response(trial,CR)=loc;
                RT(trial,CR)=round(keyTime-RTadj);
                % show feedback
                Eyelink2('Command',sprintf('draw_box %d %d %d %d %d',eye_window{loc+1}+[-15 -15 15 15],ec.YELLOW));
                if response(trial,CR)==goal(trial,CR)
                    Screen('DrawTexture',w,OK,[],tgt_rect(loc,:));%
                    correct(trial,CR)=1;
                else
                    Screen('DrawTexture',w,NG,[],tgt_rect(loc,:));%
                    correct(trial,CR)=0;
                end
                percor=nanmean(correct(correct>=0))*100;
                Screen('flip',w,0,1,2);% dont clear  & don't sync at all
                %update CR is last
                CR=min(tgt_cnt, CR+1);
            end
            %% report is last thing
            if   state ~= r_state & index>1%| event_time>=r_time%&  0| r_TR==ceil(event_time/TR)(floor(event_time)>=r_time+1000  |
                r_time=event_time+20000000;
                %r_TR=ceil(event_time/TR)+1;
                r_state=state;
                count = {sprintf('  State: %s\n Trial#:%3d of %3d ',t_state{state},trial,max_trials)};               
                if trial>0
                    T_A='';T_B='';T_C='';
                    if state<S.OUTCOME && trial>2
                        count{2} = sprintf('(data for trial-1)\n');
                        for ii =1:tgt_cnt
                            T_A=[T_A sprintf('    RT%d:%3d',ii, RT(trial-1,ii))]; %#ok<AGROW>
                            T_B=[T_B sprintf('  resp%d:%2d ',ii, response(trial-1,ii))];%#ok<AGROW>
                            T_C=[T_C sprintf('  goal%d:%2d ',ii, goal(trial-1,ii))];%#ok<AGROW>
                        end
                    else
                        count{2} = sprintf('(data for trial)\n');
                        for ii =1:tgt_cnt
                            T_A=[T_A sprintf('    RT%d:%3d',ii, RT(trial,ii))];%#ok<AGROW>
                            T_B=[T_B sprintf('  resp%d:%2d ',ii, response(trial,ii))];%#ok<AGROW>
                            T_C=[T_C sprintf('  goal%d:%2d ',ii, goal(trial,ii))];%#ok<AGROW>
                        end
                    end
                    count{3} = sprintf('%s\n',T_A);
                    count{4} = sprintf('%s\n',T_B);
                    count{5} = sprintf('%s\n',T_C);
                end
                %fprintf('%s \n',['    TR: ' num2str(ceil(event_time/TR)) ]);
                count{6} = sprintf('Correct:%4.1f%% (last5=%4.1f%%)\n',percor,last5);
                count{7} = sprintf('  Trial:%3d of%3d\n',trial,max_trials);
                count{8} = sprintf('T  Slip: %3d\n', change_state_time(index,2)-state_start_time(index));
                update_info(h2,count);
            end % report
            %% %%%%%%%%%
            event_time=round(GetSecs*1000-abs_start_time);
            %% for timing each loop...  0.1 ms is average
            fred=round(GetSecs*10000)-fred;
            if fred<length(my_timer)
                my_timer(fred+1)=my_timer(fred+1)+1;
            else
                my_timer(end)=my_timer(end)+1;
            end            
        end %while event_time < state_end_time(index)
        
        %%
        if state < S.ENDTASK,
            % EXITING WHICH STATE?
            switch state
                %case S.WAIT
                case S.FIX% just left fix state so eye must be on fix
                    if ~IsInRect(ex(eyesample),ey(eyesample), eye_window{1});% fix
                        response(trial,1)=-9; % you fecked up!
                        beep;
                    end
                    %case S.OBJECT1
                    %case S.OBJECT2
                    %case S.OBJECT3
                    %case S.OBJECT4
                    %case S.OBJECT5
                    %case S.OBJECT6
                    %case S.MASK
                case S.RESPONSE% just left response state so wipe buffer and check for responses
                    outtext='';
                    response(trial,response(trial,:)<0)=0;
                    correct(trial,correct(trial,:)<0)=0;
                    if any(response(trial,:)==0)%it means you didn't respond
                        outtext='TOO SLOW';
                    else
                        if sum(correct(trial,:))==tgt_cnt
                            outtext='Good Job';
                        else
                            outtext=sprintf('%d of %d',sum(correct(trial,:)),tgt_cnt);
                        end
                    end
                    Screen('fillrect',w,c.BACKGROUND);
                    DrawFormattedText(w,outtext,'center',centertextY,c.BLUE);
                    
                case S.OUTCOME %just left last state in a trial
                    Eyelink2('Message', sprintf('TRIAL_END#%3d: Time=%8d',trial,event_time));
                    last5=single(correct(max(trial-5,1):trial,:)>0);
                    last5=mean(last5(:))*100;
                    %case S.ENDTASK
            end % switch exit state
            
            % CHANGE STATE
            index=index+1;
            state=state_event(index);
            tstamp=Screen('flip',w);
            event_time=round(tstamp*1000-abs_start_time);           
            Eyelink2('Message', sprintf('STATE#%2d: %9s START=%8d',state,t_state{state},event_time));% requires SPRINTF
            change_state_time(index,:)=[single(state) event_time];
            
            %UPDATE FOR NEW STATE (mostly for EL1K)
            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',[0 0 c_x c_y]*2,ec.BACKGROUND));% should auto draw blank....
            switch state
                case S.FIX,
                    trial=trial+1; % global trials
                    Eyelink2('Message', sprintf('TRIAL_START#%3d: Time=%8d',trial,event_time));
                    CR=1; %Current reaction time
                    Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',fix_a+[-15 -15 15 15],ec.BLACK));
                    Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',fix_b+[-5 -5 5 5],ec.BACKGROUND));
                    
                case {S.OBJECT1 S.OBJECT2 S.OBJECT3 S.OBJECT4 S.OBJECT5 S.OBJECT6}
                    whichObj= find(state_event(index)==[S.OBJECT1 S.OBJECT2 S.OBJECT3 S.OBJECT4 S.OBJECT5 S.OBJECT6]);
                    switch OSI
                        case 0 % Object
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',fix_rect,ec.OBJ(tgts(trial,whichObj))) );
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',fix_b,ec.BLACK));
                            Eyelink2('Command',sprintf('draw_text %d %d %d #%d ',eye_window{1}([1 2]),ec.L_GREY,whichObj));
                        case 1 % Spatial
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',tgt_rect(goal(trial,whichObj),:),ec.L_GREY));
                            Eyelink2('Command',sprintf('draw_text %d %d %d #%d ',tgt_rect(goal(trial,whichObj),[1 2]),ec.BLACK,goal(trial,whichObj)));
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',fix_a,ec.BLACK));
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',fix_b,ec.BACKGROUND));
                        case 2 % Instructed
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',fix_a,ec.BLACK));
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',fix_b,ec.BACKGROUND));
                            Eyelink2('Command',sprintf('draw_text %d %d %d %s ',round(c_x),round(c_y)-30,ec.L_GREEN,loc_text{goal(trial,whichObj)}));
                    end
                    
                case {S.BLANK1 S.BLANK2 S.BLANK3 S.BLANK4 S.BLANK5 S.BLANK6}
                    switch OSI
                        case 0 % Object
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',fix_b,ec.BLACK));
                        case 1 % Spatial
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',fix_a+ec.BLACK));
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',fix_b,ec.BACKGROUND));
                        case 2 % Instructed
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',fix_a,ec.BACKGROUND));
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',fix_b,ec.BLACK));
                    end
                    
                case S.MASK
                    Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',fix_rect,ec.L_GREY));
                    Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',fix_b,ec.BLACK));
                    
                case S.RESPONSE
                    RTadj=event_time;
                    Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',fix_b,ec.BLACK));
                    switch OSI
                        case 0 % Object
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',tgt_rect(disp_loc(trial,1),:)+[-20 -20 20 20],ec.OBJ(disp_obj(trial,1)) ));
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',tgt_rect(disp_loc(trial,2),:)+[-20 -20 20 20],ec.OBJ(disp_obj(trial,2)) ));
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',tgt_rect(disp_loc(trial,3),:)+[-20 -20 20 20],ec.OBJ(disp_obj(trial,3)) ));
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',tgt_rect(disp_loc(trial,4),:)+[-20 -20 20 20],ec.OBJ(disp_obj(trial,4)) ));
                        case {1 2} % Spatial; case 2 % Instructed
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',tgt_rect(disp_loc(trial,1),:)+[-20 -20 20 20],ec.M_GREY ));
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',tgt_rect(disp_loc(trial,2),:)+[-20 -20 20 20],ec.M_GREY ));
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',tgt_rect(disp_loc(trial,3),:)+[-20 -20 20 20],ec.M_GREY ));
                            Eyelink2('Command',sprintf('draw_filled_box %d %d %d %d %d',tgt_rect(disp_loc(trial,4),:)+[-20 -20 20 20],ec.M_GREY ));
                    end %switch OSI
                    
                case S.OUTCOME
                    Eyelink2('Command',sprintf('draw_text %d %d %d %s ',round(c_x),round(c_y)-100,ec.TTEXT,outtext));
            end % switch new state
            %fred{state}(end+1)=(GetSecs*1000-abs_start_time)-event_time;          
        end %if state < S.ENDTASK,
    end %while state < S.ENDTASK
catch badness
    badness.message
    [badness.stack.line] %#ok<NOPTS>
    fprintf(' task crashed but trying to save data\n\n')
    Eyelink2('Command','clear_screen 0');
    Eyelink2('Command',sprintf('draw_text %d %d %d %s ',round(c_x),round(c_y)-60,ec.L_GREY,'CRASH!'));
    
end % first try
try % safety net for screen
    KbQueueStop();
    pause(1)
    KbQueueRelease();
    ListenChar(0);
    
    %% Stoprecording
    Eyelink2('Command','clear_screen 0');
    Eyelink('Stoprecording');
    Eyelink2('CloseFile');
    Eyelink2('Command',sprintf('draw_text %d %d %d %s ',round(c_x),round(c_y)-60,ec.L_GREY,'thank you!'));
    Eyelink2('Command',sprintf('draw_text %d %d %d %s ',round(c_x),round(c_y)+60,ec.L_GREY,'please rest.'));
    update_info(h2,{sprintf(' thank you\nplease rest')});
    
    fprintf('stop recording\n');
    % fade to grey
    Screen('TextSize',w,58);
    ctemp=(c.M_GREY-c.BACKGROUND)./80;
    for i = 1:80 % fade to ?_GREY algorythm
        Screen('fillrect',w,round(c.BACKGROUND+(ctemp*i)));
        DrawFormattedText(w,'thank you!','center',(centertextY)-60,c.BLUE);
        DrawFormattedText(w,'please rest.','center',(centertextY)+60,c.BLUE);
        Screen('flip',w);
    end
    clear Objects
    clear ctemp    
    %%
    %drawnow
    %consolidate and save data at end
    A=[];
    A.file_name=file_name;
    A.where=wherearewe;
    A.which=task;
    A.parameters=Parameters;
    A.eye_used=eye_used;
    A.colors=c;
    A.EL1kcolors=ec;
    A.states=S;
    A.t_state=t_state;
    A.state_event=state_event;
    A.state_duration=state_duration;
    A.state_end_time=state_end_time;
    A.state_start_time=state_start_time;
    A.change_state_time=change_state_time;
    %[single(state_event) state_start_time change_state_time change_state_time(:,2)- state_start_time]
    %A.INT_5=INT_5;% magnet trigger
    A.disp_obj=disp_obj;
    A.disp_loc=disp_loc;
    A.tgts=tgts;
    A.goal=goal;
    A.loc_text=loc_text;
    A.response=response;
    A.correct=correct;
    A.RT=RT;
    save([file_name '.mat'],'A');
    fprintf('Data saved: %s\n',file_name)
    update_info(h2,{sprintf('Data saved: %s\n',file_name)});
    Eyelink2('Command','clear_screen 0');
    Eyelink2('Command',sprintf('draw_text %d %d %d %s ',round(c_x),round(c_y),ec.L_GREY,'Transfering data'));
    ReceiveFilestatus = Eyelink2('ReceiveFile',[edf_name '.edf'],[file_name '.edf']);%, ['dest_is_path']
    fprintf('Transferred filesize: %3.0fKB\n', ReceiveFilestatus/2^10);
    pause(1);
    Screen('closeall');
    update_info(-1);
    ShowCursor;
    Eyelink2('Command','clear_screen 0');
    %Eyelink2('SetOfflineMode');
    Eyelink2('Shutdown');
    fprintf('END\n');
catch striketwo
    striketwo.message
    [striketwo.stack.line] %#ok<NOPTS>
    Screen('closeall');
    ShowCursor;    
    fprintf(' failed to save data\n do it manually\n')
end
%%
my_range=single(.1:.1:200)-.05;
round(my_range(find(my_timer>0,1,'last'))*1.3)
figure(1);bar(my_range,my_timer,'r')
ylim([0 100])
xlim([0 round(my_range(find(my_timer>0,1,'last'))*1.3)])
slip=change_state_time(:,2)- state_start_time;
for ii = 1:length(t_state)
    meanslip(ii)=mean(slip(single(state_event)==ii)); %#ok<SAGROW>
end
    
%sum(my_timer(my_range>2))/sum(my_timer)*100;
ListenChar(0);
clear mex
clear persistent
clear global

